package jmind.core.support;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

import jmind.core.lang.Pair;
import jmind.core.log.LogUtil;
import jmind.core.mail.SendMail;
import jmind.core.util.GlobalConstants;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

/**
 * http://sendcloud.sohu.com/
 * http://sendcloud.sohu.com/doc/downloads/code/java/java/#smtp
 * @author xieweibo
 *
 */
public class SendcloudMail {

    private static final String API_USER = "shaoganxu";
    private static final String API_KEY = "LygJNQy8k8HfvkYp";
    private static final String SEND_URL = "http://sendcloud.sohu.com/webapi/mail.send.json";
    private static final String FROM_NAME = "leshi";
    private static final String FROM_MAIL = "boss@mail.letv-club.com";
    private static final Logger logger = LogUtil.getLogger(SendcloudMail.class);

    public static void main(String[] args) {
        boolean b = sendBySMTP("weiboxie@163.com,xieweibo@letv.com,154790082@qq.com", "这是标题",
                "尊敬的乐视会员 xieweibo，您好，您的账号快要到期，请您及时续费，继续畅享乐视大片。");
        System.err.println(b);
        //    sendByApi("154790082@qq.com", "这是标题", "尊敬的乐视会员 xieweibo，您好，您的账号快要到期，请您及时续费，继续畅享乐视大片。");

    }

    public static boolean sendBySMTP(String to, String subject, String body) {
        return SendMail.sendBySMTP("smtpcloud.sohu.com", API_USER, API_KEY, to, FROM_MAIL, FROM_NAME, subject, body,
                null);

    }

    public static boolean sendByApi(String to, String subject, String body) {
        List<Pair<String, String>> params = Lists.newArrayList();
        params.add(Pair.of("api_user", API_USER));
        params.add(Pair.of("api_key", API_KEY));
        params.add(Pair.of("from", FROM_MAIL));
        params.add(Pair.of("fromname", FROM_NAME));
        params.add(Pair.of("to", to));
        params.add(Pair.of("subject", subject));
        params.add(Pair.of("html", body));
        //     返回email id
        //    params.add(Pair.of("resp_email_id", "true"));
        String res = HttpUtil.post(SEND_URL, params, GlobalConstants.ENCODE);
        if (res != null && res.contains("success")) {
            return true;
        }
        logger.error("send mail to={},res={}", to, res);
        return false;
    }

    /**
     * 
     * @param tos 接收邮件列表
     * @param sub 变量
     * @param subject 主题
     * @param template 模板名称
     * @return
     *   List<String> tos = Lists.newArrayList("154790082@qq.com", "xieweibo@letv.com", "weiboxie@163.com");
        Map<String, Object> sub = Maps.newHashMap();
        List<String> names = Lists.newArrayList("波波", "韦博", "大爷");
        sub.put("%name%", names);
        sendTemplate(tos, sub, "续费提醒", "xufei_template");
     */
    public static boolean sendTemplate(List<String> tos, Map<String, ?> sub, String subject, String template) {
        JSONObject vars = new JSONObject();
        vars.put("to", tos); // 接收邮件列表
        vars.put("sub", sub); // 变量列表
        List<Pair<String, String>> params = Lists.newArrayList();
        params.add(Pair.of("api_user", API_USER));
        params.add(Pair.of("api_key", API_KEY));
        params.add(Pair.of("from", FROM_MAIL));
        params.add(Pair.of("fromname", FROM_NAME));
        params.add(Pair.of("substitution_vars", vars.toJSONString()));
        params.add(Pair.of("template_invoke_name", template));
        params.add(Pair.of("subject", subject));
        // 返回email id
        //    params.add(Pair.of("resp_email_id", "true"));
        String res = HttpUtil.post("http://sendcloud.sohu.com/webapi/mail.send_template.json", params,
                GlobalConstants.ENCODE);
        if (res != null && res.contains("success")) {
            return true;
        }
        logger.error("send mail to={},res={}", template, res);
        return false;
    }

    /**
     * 发送附件
     * http://sendcloud.sohu.com/doc/downloads/code/java/java/#webapi_1
     */
    @SuppressWarnings("resource")
    public static void send_common_with_attachment(String to) throws ClientProtocolException, IOException {

        final String url = "http://sendcloud.sohu.com/webapi/mail.send.json";

        HttpPost httpPost = new HttpPost(url);
        HttpClient httpclient = new DefaultHttpClient();

        // 涉及到附件上传, 需要使用 MultipartEntity
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                Charset.forName("UTF-8"));
        entity.addPart("api_user", new StringBody(API_USER, Charset.forName("UTF-8")));
        entity.addPart("api_key", new StringBody(API_KEY, Charset.forName("UTF-8")));
        entity.addPart("to", new StringBody(to, Charset.forName("UTF-8")));
        entity.addPart("from", new StringBody("sendcloud@sendcloud.org", Charset.forName("UTF-8")));
        entity.addPart("fromname", new StringBody("SendCloud", Charset.forName("UTF-8")));
        entity.addPart("subject", new StringBody("SendCloud java common attachment", Charset.forName("UTF-8")));
        entity.addPart("html", new StringBody("欢迎使用SendCloud", Charset.forName("UTF-8")));
        entity.addPart("resp_email_id", new StringBody("true"));

        // 添加附件
        File file = new File("/path/file");
        FileBody attachment = new FileBody(file, "application/octet-stream", "UTF-8");
        entity.addPart("files", attachment);

        // 添加附件, 文件流形式
        // File file = new File("/path/file");
        // String attachName = "attach.txt";
        // InputStreamBody is = new InputStreamBody(new FileInputStream(file),
        // attachName);
        // entity.addPart("files", is);

        httpPost.setEntity(entity);

        HttpResponse response = httpclient.execute(httpPost);
        // 处理响应
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 正常返回, 解析返回数据
            System.out.println(EntityUtils.toString(response.getEntity()));
        } else {
            System.err.println("error");
        }
        httpPost.releaseConnection();
    }

}
